<template>
	<el-dialog :model-value="visible" title="分配角色" :before-close="beforeClose">
		<el-form :model="roleForm">
			<el-form-item>
				<el-select v-model="roleForm" multiple collapse-tags :max-collapse-tags="100" style="width: 240px">
					<el-option v-for="item in roleInfo" :value="item.id" :label="item.name" :key="item.id" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleCancel">取消</el-button>
				<el-button type="primary" @click="handleCancelEdit">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch } from "vue";
import type { getRoleInfoItem } from "@/types/global";
import type { Ref } from "vue";
import * as role from "@/request/modules/role";
// 接收父传过来的参数
const props = defineProps<{ visible: boolean; form: number[] }>();
const roleForm = ref([]) as Ref<number[]>;
const originForm = ref([]) as Ref<number[]>;
// 接收请求的所有角色列表
const roleInfo = ref([]) as Ref<getRoleInfoItem[]>;
const roleList = async () => {
	let listAll = await role.getListAllAPI();
	roleInfo.value = listAll;
};

roleList();
watch(
	() => {
		return props.form;
	},
	(newVal) => {
		roleForm.value = [...newVal];
		originForm.value = [...newVal];
	},
	{ immediate: true }
);
const emit = defineEmits<{
	(event: "cancel"): void;
	(event: "confirm", roleForm: number[]): void;
}>();
// 取消
const handleCancel = () => {
	emit("cancel");
	roleForm.value = [...originForm.value];
};
// 确定
const handleCancelEdit = () => {
	emit("confirm", roleForm.value);
};
// 模态框关闭前的回调
const beforeClose = () => {
	handleCancel(); //重新调用关闭的事件
};
</script>

<style scoped></style>
